package com.itlong.cloud.operate.service.impl;

import com.itlong.cloud.POJO.DTO.operate.OperateDeviceAuthCodeGetDevicePageDTO;
import com.itlong.cloud.POJO.DTO.operate.OperateDeviceAuthCodeGetPageDTO;
import com.itlong.cloud.POJO.PO.DevicePadAuthCodePO;
import com.itlong.cloud.POJO.VO.operate.OperateDeviceAuthCodeGetDevicePageVO;
import com.itlong.cloud.POJO.VO.operate.OperateDeviceAuthCodeGetPageVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.enumerate.DataStatusEnum;
import com.itlong.cloud.operate.dao.IOperateDeviceAuthCodeDao;
import com.itlong.cloud.operate.service.IOperateDeviceAuthCodeService;
import com.itlong.cloud.utils.data.handler.SqlUtil;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.random.LogicIdUtil;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <desc>
 *      设备授权码管理服务层接口实现类
 * </desc>
 *
 * @createDate 2019/01/16
 */
@Service
public class OperateDeviceAuthCodeServiceImpl implements IOperateDeviceAuthCodeService {

    @Autowired
    private IOperateDeviceAuthCodeDao iOperateDeviceAuthCodeDao;

    /**
     * <desc>
     *      分页获取设备授权码
     * </desc>
     *
     * @param operateDeviceAuthCodeGetPageDTO 获取设备授权码列表DTO
     * @return 分页获取结果
     * @author wangzhi
     * @createDate 2019/01/16
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public Page<OperateDeviceAuthCodeGetPageVO> getPage(OperateDeviceAuthCodeGetPageDTO operateDeviceAuthCodeGetPageDTO) throws Exception {
        Map<String,Object> params = SqlUtil.convertBeanToMapParams(operateDeviceAuthCodeGetPageDTO);
        Page<OperateDeviceAuthCodeGetPageVO> page = new Page<>();
        page.getPage().setPageSize(operateDeviceAuthCodeGetPageDTO.getPageSize());
        page.getPage().setCurrentPage(operateDeviceAuthCodeGetPageDTO.getCurrentPage());
        params.put("startSlip", page.getPage().getStartSlip());
        params.put("pageSize", page.getPage().getPageSize());
        List<OperateDeviceAuthCodeGetPageVO> operateDeviceAuthCodeGetPageVOS = iOperateDeviceAuthCodeDao.getPage(params);
        page.setRows(operateDeviceAuthCodeGetPageVOS,iOperateDeviceAuthCodeDao.getRecordCount(params));
        return page;
    }

    /**
     * <desc>
     *      新增设备授权码
     * </desc>
     *
     * @param baiduAuthCode 百度识别授权码，多个用英文逗号相连
     * @return 1成功，0失败
     * @author wangzhi
     * @createDate 2019/01/16
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Integer saveDeviceAuthCode(String baiduAuthCode) throws Exception {
        Date nowTime = new Date();
        List<DevicePadAuthCodePO> devicePadAuthCodePOList = new ArrayList<>();
        List<String> baiduAuthCodeList = StringHandlerUtil.splitStringList(baiduAuthCode);
        for (String authCode : baiduAuthCodeList){
            DevicePadAuthCodePO devicePadAuthCodePO = new DevicePadAuthCodePO();
            devicePadAuthCodePO.setCodeId(LogicIdUtil.bussinessId());
            devicePadAuthCodePO.setBaiduAuthCode(authCode);
            devicePadAuthCodePO.setUseStatus(1);
            devicePadAuthCodePO.setStatus(DataStatusEnum.NORMAL.getType());
            devicePadAuthCodePO.setCreateTime(nowTime);
            devicePadAuthCodePO.setUpdateTime(nowTime);
            devicePadAuthCodePOList.add(devicePadAuthCodePO);
        }
        return iOperateDeviceAuthCodeDao.batchSaveDeviceAuthCode(devicePadAuthCodePOList);
    }

    /**
     * <desc>
     *      查询单个设备授权码
     * </desc>
     *
     * @param operateDeviceAuthCodeGetPageDTO 获取设备授权码列表DTO
     * @return 单个设备授权码
     * @author wangzhi
     * @createDate 2019/01/21
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public OperateDeviceAuthCodeGetPageVO getOne(OperateDeviceAuthCodeGetPageDTO operateDeviceAuthCodeGetPageDTO) throws Exception {
        Map<String,Object> params = SqlUtil.convertBeanToMapParams(operateDeviceAuthCodeGetPageDTO);
        return iOperateDeviceAuthCodeDao.getOne(params);
    }

    /**
     * <desc>
     *      获取设备授权码相关设备列表
     * </desc>
     *
     * @param operateDeviceAuthCodeGetDevicePageDTO 获取设备授权码相关设备列表DTO
     * @return 获取设备授权码相关设备列表分页结果
     * @author wangzhi
     * @createDate 2019/03/12
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public Page<OperateDeviceAuthCodeGetDevicePageVO> getDevicePage(OperateDeviceAuthCodeGetDevicePageDTO operateDeviceAuthCodeGetDevicePageDTO) throws Exception {
        Map<String,Object> params = SqlUtil.convertBeanToMapParams(operateDeviceAuthCodeGetDevicePageDTO);
        Page<OperateDeviceAuthCodeGetDevicePageVO> page = new Page<>();
        page.getPage().setPageSize(operateDeviceAuthCodeGetDevicePageDTO.getPageSize());
        page.getPage().setCurrentPage(operateDeviceAuthCodeGetDevicePageDTO.getCurrentPage());
        params.put("startSlip", page.getPage().getStartSlip());
        params.put("pageSize", page.getPage().getPageSize());
        List<OperateDeviceAuthCodeGetDevicePageVO> operateDeviceAuthCodeGetDevicePageVOS = iOperateDeviceAuthCodeDao.getDevicePage(params);
        page.setRows(operateDeviceAuthCodeGetDevicePageVOS,iOperateDeviceAuthCodeDao.getDeviceRecordCount(params));
        return page;
    }

    /**
     * <desc>
     *      购买（设备绑定设备授权码）
     * </desc>
     *
     * @param projectId    项目编号
     * @param deviceUnique 设备序列号，多个逗号相连
     * @return 0-失败 1-成功
     * @author wangzhi
     * @createDate 2019/03/12
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Integer buy(String projectId, String deviceUnique) throws Exception {
        List<String> deviceUniqueList = StringHandlerUtil.splitStringList(deviceUnique);
        // 数据库中查询可用的设备授权码
        List<DevicePadAuthCodePO> devicePadAuthCodePOS = iOperateDeviceAuthCodeDao.getUsableAuthCode(deviceUniqueList.size());
        // 库存不够则购买失败
        if (devicePadAuthCodePOS == null || devicePadAuthCodePOS.isEmpty() || !(devicePadAuthCodePOS.size() == deviceUniqueList.size())) {
            return 0;
        }
        List<Map<String, Object>> updateList = new ArrayList<>();
        for (int i = 0; i < devicePadAuthCodePOS.size(); i++) {
            DevicePadAuthCodePO devicePadAuthCodePO = devicePadAuthCodePOS.get(i);
            devicePadAuthCodePO.setProjectId(projectId);
            devicePadAuthCodePO.setDeviceUnique(deviceUniqueList.get(i));
            devicePadAuthCodePO.setUpdateTime(new Date());
            updateList.add(SqlUtil.durableData(devicePadAuthCodePO, PlatformConstants.TABLE_UPDATE));
        }
        iOperateDeviceAuthCodeDao.batchUpdate(updateList);
        return 1;
    }

    /**
     * <desc>
     *      解绑（设备与设备授权码解除绑定）
     * </desc>
     *
     * @param operateDeviceAuthCodeGetPageDTO 获取设备授权码列表DTO
     * @return 0-失败 1-成功
     * @author wangzhi
     * @createDate 2019/03/12
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Integer unbind(OperateDeviceAuthCodeGetPageDTO operateDeviceAuthCodeGetPageDTO) throws Exception {
        DevicePadAuthCodePO devicePadAuthCodePO = iOperateDeviceAuthCodeDao.getAuthCodeByCodeId(operateDeviceAuthCodeGetPageDTO.getCodeId());
        if (devicePadAuthCodePO == null || devicePadAuthCodePO.getUseStatus() == null || devicePadAuthCodePO.getUseStatus() == 0) {
            return 0;
        }
        // 当设备购买授权码且激活(已使用状态)，后台点击解绑后，状态变为报废，解除设备机号与授权码的关联
        if (devicePadAuthCodePO.getUseStatus() == 2) {
            devicePadAuthCodePO.setUseStatus(0);
        // 当设备购买授权码且未激活(未使用状态)，后台点击解绑后，状态变为未使用，解除设备机号与授权码的关联，记录不清除，该激活码未被使用可以再次被购买
        } else if (devicePadAuthCodePO.getUseStatus() == 1) {
            devicePadAuthCodePO.setUseStatus(1);
        }
        devicePadAuthCodePO.setProjectId(null);
        devicePadAuthCodePO.setDeviceUnique(null);
        devicePadAuthCodePO.setUpdateTime(new Date());
        iOperateDeviceAuthCodeDao.unbind(devicePadAuthCodePO);
        return 1;
    }
}
